from datetime import datetime
import json
import time
import cv2
import numpy as np
import requests
from os import path
# settings
from schema.img import CreateImg
from schema.qm import CreateQm
from service.dev_service import get_cvinfo_by_station_name, update_dev_state
from service.img_service import create_img
from service.qm_service import create_qm_data 
# loguru
from loguru import logger
# conf
from conf import conf
from tornado import tornadoIns



async def save_to_db(cvinfo,station,timestamp,state_text,temp_text = None,humi_text =None):

    # 将采集的图片数据存入数据库
    img = CreateImg(created_at=datetime.fromtimestamp(timestamp),
                    name=str(timestamp),
                    dev_id=cvinfo.dev_id,
                    station_id=cvinfo.station_id,
                    content_temperature=float(temp_text) if temp_text else None,
                    content_humidity=float(humi_text) if humi_text else None,
                    content_status=state_text
                    )


    # 将照片信息保存到数据库中
    await create_img(img)

    # 修改机台的状态,修改数据中的几台的状态,同时发送socket请求到前端，修改前端界面的几台状态
    await update_dev_state(cvinfo.dev_id,state_text,timestamp,False)


    qm_obj = CreateQm(dev_no=cvinfo.dev_no,
                      station_no = int(station.split("LM")[1]),
                      created_at=datetime.fromtimestamp(timestamp),
                      name=str(timestamp),
                      state=state_text,
                      temp=float(temp_text) if temp_text else None,
                      humi=float(humi_text) if humi_text else None,
                      ) 

    create_qm_data(qm_obj)
                








    



